<template>
  <div>
    <vxe-toolbar
      id="toolbarId_bi3"
      :custom="{ storage: true }"
      export
      :refresh="{ query: findList }"
    >
      <template v-slot:buttons>
        <el-button @click="funcFilter">查询</el-button>
        <el-button  @click="funcAdd">新增</el-button>
        <el-button v-if="isAdmin && isTopBranch" @click="funcheckQuire">设置必填项</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      highlight-hover-row
      row-id="id"
      height="700"
      :show-footer="true"
      :footer-method="footerMethod"
      :loading="loading"
      :data="tableData"
      :sort-config="{ remote: true }"
      export-config
      show-overflow
      align="center"
      @sort-change="sortList"
    >
      <vxe-table-column type="checkbox" width="60"/>
      <vxe-table-column>
        <vxe-table-column  field="branchCode"  title="机构" :formatter="formatterBranch" min-width="200"  sortable />
        <template v-slot:header>
          <el-select v-model="listQuery.branchCode" placeholder="请选择" clearable>
            <el-option v-for="item in branchList" :key="item.code" :label="item.groupName" :value="item.code"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="authStatus"
          title="审核状态"
          :formatter="formatterAuthStatus"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.authStatus" clearable placeholder="请选择">
            <el-option
              v-for="item in authStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="companyName" title="企业名称" min-width="130" sortable />
        <template v-slot:header>
          <el-input v-model="listQuery.companyName" placeholder="请输入企业名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="phone" title="联系方式" min-width="130" sortable />
        <template v-slot:header>
          <el-input v-model="listQuery.phone" placeholder="请输入联系方式" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="isCtms">
        <vxe-table-column field="taxPoint" title="税点(%)" min-width="200" sortable />
        <template v-slot:header>
          <el-row>
            <el-col :span="11">
              <el-input type="number" v-model="listQuery.taxPointStart" placeholder="下限" clearable />
            </el-col>
            <el-col :span="11" :offset="2">
              <el-input type="number" v-model="listQuery.taxPointEnd" placeholder="上限" clearable />
            </el-col>
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="isMonthlyClient"
          :formatter="formatterCommonStatus"
          title="是否月结"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.isMonthlyClient" clearable placeholder="请选择">
            <el-option
              v-for="item in commonStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="isCtms">
        <vxe-table-column
          field="isIndependentCheckout"
          title="是否独立核算"
          :formatter="formatterCommonStatus"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.isIndependentCheckout" clearable placeholder="请选择">
            <el-option
              v-for="item in commonStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="amount" title="账户金额(元)" min-width="200" sortable />
        <template v-slot:header>
          <el-row>
            <el-col :span="11">
              <el-input type="number" v-model="listQuery.amountStart" placeholder="下限" clearable />
            </el-col>
            <el-col :span="11" :offset="2">
              <el-input type="number" v-model="listQuery.amountEnd" placeholder="上限" clearable />
            </el-col>
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="isCtms">
        <vxe-table-column field="ensureFee" title="保证金基准(元)" min-width="200" sortable />
        <template v-slot:header>
          <el-row>
            <el-col :span="11">
              <el-input type="number" v-model="listQuery.ensureFeeStart" placeholder="下限" clearable />
            </el-col>
            <el-col :span="11" :offset="2">
              <el-input type="number" v-model="listQuery.ensureFeeEnd" placeholder="上限" clearable />
            </el-col>
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="isCtms">
        <vxe-table-column field="ensureFeeAmount" title="保证金余额(元)" min-width="200" sortable />
        <template v-slot:header>
          <el-row>
            <el-col :span="11">
              <el-input type="number" v-model="listQuery.ensureFeeAmountStart" placeholder="下限" clearable />
            </el-col>
            <el-col :span="11" :offset="2">
              <el-input type="number" v-model="listQuery.ensureFeeAmountEnd" placeholder="上限" clearable />
            </el-col>
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          title="创建时间"
          min-width="420"
          sortable
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="authTime"
          title="审核时间"
          min-width="420"
          sortable
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtAuthRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'authTime')"
          />
        </template>
      </vxe-table-column>

      <vxe-table-column title="操作" width="240" fixed="right"  field="action">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="申请DIS" placement="top" v-if="showApplyDisBtn(scope.row)">
            <vxe-button type="text" @click="funcApply(scope.row.partyCode)">
              <i class="el-icon-connection" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :page-sizes="Pagingconf"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
      @page-change="handlePageChange"
    />
  </div>
</template>
<script>
  import { getRole } from '@/utils/getRole';
  import { getShipperList, delShipperInfo, maYiBlockChain } from "@/api/shipment";
  import request from "@/utils/request";
  export default {
    name: "ShipmentCompanyList",
    data() {
      return {
        isCtms: true,//默认显示 同城系统时隐藏
        branch: this.$store.getters.branch,
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        },
        loading: false,
        tableData: [],
        gmtCreatedRange: "",
        gmtAuthRange: "",
        listQuery: {
          staffType: "1", // 类型(企业)
          pageNum: 1,
          pageSize: 20,
          sortField: "",
          sortType: "",
          total: 0
        },
        Pagingconf: [],
        sumObject: {
          freezingAmount: 0,
          amount: 0,
          ensureFeeAmount: 0
        },
        // 审核状态
        authStatusList: [
          { label: "未审核", value: 0 },
          // { label: "审核中", value: 1 },
          { label: "审核未通过", value: 2 },
          { label: "审核通过", value: 3 }
        ],
        // 通用是否状态
        commonStatusList: [
          { label: "否", value: 0 },
          { label: "是", value: 1 }
        ],
        // 是否admin
        isAdmin:false,
        //机构信息
        branchList: this.$store.state.components.branchList,
        // 是否顶级机构
        isTopBranch: false,
      };
    },
    created() {
      const partyType = this.$store.getters.party.partyType
      this.isAdmin = partyType == 'SUPER_ADMIN' || partyType == 'PLAT_ADMIN' || partyType == 'STAFF'
      this.findList();
      this.isCtmsShow = getRole();//获取登录用户登录的是否是同城系统
      this.dataBranch = JSON.parse(localStorage.getItem('dataBranch'));
      this.platformDid = this.dataBranch.platformDid;
      this.openMaYiBlockChain = this.dataBranch.partyGroupConfigCacheMap.MaYiBlockChainConfig_useMaYiBlockChain.configValue == 1 ? true : false;
      this.isTopBranch = this.dataBranch.level == 0;
    },
    methods: {
      showApplyDisBtn(row) {
        if (!this.openMaYiBlockChain || this.isCtmsShow) {
          return false;
        }
        let hasDid = !(typeof this.platformDid == "undefined" || this.platformDid == '');
        return hasDid && row.authStatus == 3 && (row.szwlDid == null || row.szwlDid == '');
      },
      findList() {
        return new Promise(resolve => {
          this.loading = true;
          getShipperList(this.listQuery).then(response => {
            resolve();
            this.tableData = response.data.records;
            this.listQuery.total = response.data.total;
            this.Pagingconf = [20, 30, 50, 100, response.data.total||1];
            this.sumObject = response.data.sumObject;
            this.loading = false;
          });
        });
      },
      // 时间
      changeDate(value, prefix) {
        if (value) {
          this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
          this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
        } else {
          this.listQuery[`${prefix}Start`] = "";
          this.listQuery[`${prefix}End`] = "";
        }
      },
      // 查询
      funcFilter() {
        this.listQuery.pageNum = 1;
        this.findList();
      },
      // 翻译机构
      formatterBranch({ cellValue }) {
        const item = this.branchList.find(item => item.code === cellValue);
        return item ? item.groupName : "";
      },
      // 排序
      sortList({ column, property, order }) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
        this.findList();
      },
      // 添加方法
      funcAdd() {
        this.$router.push({
          path: "/basicInfo/shipment/addShipmentCompanyForm",
          query:{company:'1'}
        });
      },
      // 修改方法
      funcEdit(row) {
        this.$router.push({
          path: "/basicInfo/shipment/editShipmentCompanyForm",
          query: { code: row.code, partyCode: row.partyCode, company:'1' }
        });
      },
      // 设置必填项
      funcheckQuire(row) {
        this.$router.push({
          path: "/basicInfo/shipment/addShipmentCompanyForm",
          query: {company:'1', checkQuire:true }
        });
      },
      // 详情
      funcDetail(row) {
        this.$router.push({
          path: "/basicInfo/shipment/infoShipmentCompanyForm",
          query: { code: row.code, partyCode: row.partyCode }
        });
      },
      // 删除方法
      funcDelete(codes) {
        this.$confirm("确认删除吗？")
          .then(_ => {
            delShipperInfo({ codes }).then(response => {
              this.$message({ message: response.msg, type: "success" });
              this.findList();
            });
          })
          .catch(_ => {});
      },
      // 申请DIS
      async funcApply(codes) {
        let response = await maYiBlockChain(codes)
        this.$message({ message: response.msg, type: "success" });
        this.findList();
      },
      // 翻译审核状态
      formatterAuthStatus({ cellValue }) {
        const item = this.authStatusList.find(item => item.value === cellValue);
        return item ? item.label : "";
      },
      // 翻译通用是否状态
      formatterCommonStatus({ cellValue }) {
        const item = this.commonStatusList.find(item => item.value === cellValue);
        return item ? item.label : "";
      },
      // 分页handle
      handlePageChange({ currentPage, pageSize }) {
        this.listQuery.pageNum = currentPage;
        this.listQuery.pageSize = pageSize;
        this.findList();
      },
      // 合计
      footerMethod({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return "合计";
            }
            if (column.property === "amount") {
              return this.sumObject.amount;
            }
            /*          if (column.property === "ensureFee") {
              return "待定";
            }*/
            if (column.property === "ensureFeeAmount") {
              return this.sumObject.ensureFeeAmount;
            }
            return "-";
          })
        ];
      }
    }
  };
</script>
